package com.wjb.web.backend;



import com.wjb.model.EbNews;
import com.wjb.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;


    @RequestMapping("/toSave")
    public String toSave() {
        return "manage/news-add";
    }

    /**
     * 将数据放到 model中，将页面放到view中
     * spring mvc---将model渲染到view中
     * <p>
     * list ---分页请求数据
     */

    @RequestMapping("saveCommit")
    public String saveCommit(EbNews ebNews) {
        //1.获取表单的值参数  参数效验
        if (ebNews.getEnTitle() == null || ebNews.getEnContent().trim().length() == 0) {
            return "manage/manage-error";
        }
        //2.调用Service方法保存
        int result = newsService.save(ebNews);
        if (result <1) {
            return "manage/manage-error";
        }
        return "manage/manage-result";
    }

    @RequestMapping("/{id}")
    public String delete(@PathVariable("id") Integer id){
        int result=newsService.delete(id);
        if(result==0){
            return "manage/manage-error";
        }
        return "manage/manage-result";
    }
    @RequestMapping("/edit")
    public String edit(Model model, Integer enId) {
//调用service层查询新闻所有信息
        EbNews ebNews = newsService.selectById(enId);
        //model传递与jsp指定
        model.addAttribute("ebNews", ebNews);
        return "manage/news-modify";
    }
    @RequestMapping("/editSubmit")
    public String editSubmit(EbNews ebNews){
        //更新新闻信息
        int result = newsService.updateById(ebNews);
        //跳转刷新页面
        if(result<=0){
            return "manage/manage-error";
        }
        return "manage/manage-result";
    }


    @RequestMapping("/list")
    public String list(Model model, @RequestParam(value = "page", defaultValue = "1") int psize,
                       @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        System.out.println("start service.....");
        //1.请求service层获取新闻的分页数据
        List<EbNews> newsList = newsService.listByPage(psize, pageSize);
        //d调用service层的新闻表总页数
        int totalPage = newsService.getMaxPage(pageSize);

        //2.传递model(数据)和view视图(jsp)
        model.addAttribute("newsList", newsList);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("curPage", psize);
        return "manage/news";//视图  通过manage/news.jsp进行展示数据

    }


}
